package com.wuye.web;


import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.entity.ContentType;
import org.apache.http.util.Args;
import org.apache.http.util.ByteArrayBuffer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 解决乱码问题
 * Created by xieyp on 2016-03-10.
 */
public class IOUtil {


    public static String readFileToString(File file) throws IOException {
        return readFileToString(file, null);
    }

    public static String readFileToString(File file, String defaultString) throws IOException {
        if (file.exists()) {
            try (InputStream inputStream = new FileInputStream(file)) {
                byte[] bs = new byte[(int) file.length()];
                inputStream.read(bs);
                return toString(bs);
            }
        }
        return defaultString;
    }

    /**
     * 解决乱码问题
     *
     * @param bytes
     * @return
     * @throws IOException
     */
    public static String toString(byte[] bytes) throws IOException {
        String s = new CharsetDetector(bytes).encoding;
        if (s != null)
            return new String(bytes, s);
        return new String(bytes);
    }

    public static String toString(final HttpEntity entity) throws IOException, ParseException {
        try (final InputStream in = entity.getContent()) {
            if (in == null) {
                return null;
            }
            Args.check(entity.getContentLength() <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory");
            int i = (int) entity.getContentLength();
            if (i < 0) {
                i = 4096;
            }


            final ByteArrayBuffer buffer = new ByteArrayBuffer(i);
            final byte[] tmp = new byte[1024];
            int l;
            while ((l = in.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
            byte[] bs = buffer.toByteArray();


            String s = new CharsetDetector(bs).encoding;
            if (s != null) {
                return new String(bs, s);
            }
            try {
                final ContentType contentType = ContentType.get(entity);
                if (contentType != null) {
                    return new String(bs, contentType.getCharset());
                }
            } catch (final Exception ex) {
                ex.printStackTrace();
            }
            return new String(bs);
        }
    }
}
